/*
@Time: 2025/9/22 23:20
@Author: Leslie
@Function: 用户服务层
*/

package service

import (
	"admin_api/api/dao"
	"admin_api/api/entity"
	"admin_api/common/result"
	"admin_api/common/utils"
	"admin_api/pkg/jwt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type ISysAdminService interface {
	Login(c *gin.Context, dto entity.Login)
}
type SysAdminServiceImpl struct{}

// Login 登录
func (s *SysAdminServiceImpl) Login(c *gin.Context, dto entity.Login) {
	// 登录参数校验
	err := validator.New().Struct(dto)
	if err != nil {
		result.Fail(c, int(result.ApiCode.MissingLoginParameter),
			result.ApiCode.GetMessage(result.ApiCode.MissingLoginParameter))
	}
	// 验证码是否过期
	code := utils.RedisStore{}.Get(dto.IdKey, true)
	if len(code) == 0 {
		result.Fail(c, int(result.ApiCode.VerificationCodeHasExpired),
			result.ApiCode.GetMessage(result.ApiCode.VerificationCodeHasExpired))
		return
	}
	// 校验验证码
	verifyRes := CaptVerify(dto.IdKey, dto.Image)
	if !verifyRes {
		result.Fail(c, int(result.ApiCode.CAPTCHANOTTRUE),
			result.ApiCode.GetMessage(result.ApiCode.CAPTCHANOTTRUE))
		return
	}
	// 校验
	sysAdmin := dao.SysAdminDetail(dto)
    if sysAdmin.ID == 0 {
        result.Fail(c, int(result.ApiCode.USERNOTFOUND),
            result.ApiCode.GetMessage(result.ApiCode.USERNOTFOUND))
        return
    }
	if sysAdmin.Password != utils.EncryptionMd5(dto.Password) {
		result.Fail(c, int(result.ApiCode.PASSWORDNOTTRUE),
			result.ApiCode.GetMessage(result.ApiCode.PASSWORDNOTTRUE))
		return
	}
	const status int = 2
	if sysAdmin.Status == status {
		result.Fail(c, int(result.ApiCode.STATUSISENABLE),
			result.ApiCode.GetMessage(result.ApiCode.STATUSISENABLE))
		return
	}
	// 生成token
	tokenString, _ := jwt.GenerateTokenByAdmin(sysAdmin)
	result.Success(c, map[string]interface{}{"token": tokenString, "sysAdmin": sysAdmin})
}

var sysAdminService = SysAdminServiceImpl{}

func SysAdminService() ISysAdminService {
	return &sysAdminService
}
